﻿using System;
using System.Security.Principal;
using System.Text.RegularExpressions;

namespace SSAT.UserFriendly
{
    internal static class Greeting
    {
        public static string Next()
        {
            string[] greetings = GetGreetings();
            if (greetings.Length > 0)
            {
                Random random = new Random();
                int index = random.Next(greetings.Length);
                return Format(greetings[index]);
            }
            return string.Empty;
        }

        private static string[] GetGreetings()
        {
            string greetings = Resources.Greetings;
            return !string.IsNullOrEmpty(greetings) ? greetings.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries) : new string[0];
        }

        private static string Format(string greeting)
        {
            string result = greeting;
            if (greeting.Contains(Constants.System.UserNameKey))
            {
                string currentUserName = GetUserName();
                result = Regex.Replace(greeting, Constants.System.UserNameKey, currentUserName);
            }
            return result;
        }

        private static string GetUserName()
        {
            string currentUserName = string.Empty;
            WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
            if(currentIdentity != null)
            {
                currentUserName = currentIdentity.Name;
                int indexOfDomainSeparator = currentUserName.IndexOf(Constants.System.DomainSeparator);
                if (indexOfDomainSeparator != -1)
                {
                    currentUserName = currentUserName.Substring(indexOfDomainSeparator + 1, currentUserName.Length - indexOfDomainSeparator - 1);
                }
            }
            return currentUserName;
        }
    }
}
